package cn.mhome.merchant.framework.shiro;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mhome.merchant.entity.system.param.SysUserParam;
import cn.mhome.merchant.entity.system.result.SysUserResult;
import cn.mhome.merchant.framework.data.UserAuthVO;
import cn.mhome.merchant.server.system.service.SysUserService;

@Service
public class ServerAuthorizingRealm extends AuthorizingRealm {
	protected static Logger logger = LoggerFactory
			.getLogger(ServerAuthorizingRealm.class);
	
	@Autowired
	public HttpServletRequest request;
	
	@Resource
	SysUserService sysUserService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}
	
	public String dealSystemLogin(UserAuthVO userAuthVO,int systemId){
		return "";
	}
	

	/**
	 * 登录认证，创建用户的登录信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		String username = userToken.getUsername().trim();
		String password = String.valueOf(userToken.getPassword());
		try {
			SysUserParam userParam = new SysUserParam();
			userParam.setUsername(username);
			userParam.setPassword(password);
			SysUserResult sysUserResult = sysUserService.checkUserPassword(userParam);
			if(sysUserResult != null && StringUtils.isNotBlank(sysUserResult.getUserId())){
				UserAuthVO userAuthVo = new UserAuthVO();
				userAuthVo.setUserid(Long.valueOf(sysUserResult.getUserId()));
				userAuthVo.setUsername(username);
				request.getSession().setAttribute("userJob",sysUserResult.getJob());
				request.getSession().setAttribute("userId",sysUserResult.getUserId());
				return new SimpleAuthenticationInfo(userAuthVo,userToken.getPassword(), username);
			}else{
				throw new IncorrectCredentialsException(sysUserResult.getMsg());
			}
		} catch (Exception e) {
			throw new IncorrectCredentialsException(e.getMessage());
		}
	}
}

